#ifndef VTRACE_H
#define VTRACE_H

#ifdef CONFIG_VTRACE

#include "utils.h"
#include "verilated.h"
#include "verilated_vcd_c.h"
#include "Vtop.h"

class VTrace {
private:
    Vtop* top; // Don't free!
    VerilatedContext* ctx; // Don't free!
    VerilatedVcdC* tfp;
public:
    bool enable { false };
    VTrace(const char* file, Vtop* _top, VerilatedContext* _ctx) {
        this->top = _top;
        this->ctx = _ctx;
        
        Assert(top, "top module is null!");
        Assert(ctx, "context is null!");

        Log("The wave trace file is %s", file);
        // Allow traces to at some point be enabled
        ctx->traceEverOn(true);
        // Trace the signals
        tfp = new VerilatedVcdC;
        top->trace(tfp, 1);
        tfp->open(file);
    }
    ~VTrace() {
        tfp->dump(ctx->time());
        tfp->close();
        delete tfp;
    }
    void dump() {
        // Write one cycle of dump data, Call after eval'ed
        if (enable) tfp->dump(ctx->time());
        ctx->timeInc(1);
    }
    void flush() {
        // Flush all traces
        if (enable) tfp->flush();
    }
};

#endif

#endif
